<template>
	<view class="body fcard">
		<!-- <uni-nav-bar left-icon="home-filled" @clickLeft='Tohome' status-bar='true' title="门禁二维码"></uni-nav-bar> -->
		<view class="imgBox">
			<image src="../../static/image/er.png" mode="" style="width: 200upx;height: 200upx;border-radius: 100%;border:3upx solid #2979FF;"></image>
			<text @click="setCard">设置卡号</text>
		</view>
		<view :style="{ width: width + 'px', height: width + 'px', 'margin-left': '12.5%', 'margin-top': '25rpx' }">
			<image :src="QrImage" style="width: 100%;height: 100%;"></image>
			<canvas id="qrcode" canvas-id="qrcode" :style="[{ height: width + 'px', width: width + 'px' }]" />
		</view>
		<view style="text-align: center;">
			<text style="font-size: 25rpx;"> 二维码有效期为：{{showTime}}</text>
			<text style="text-decoration: underline;color: #007AFF;" @click="popShowFun">设置</text>
		</view>
		<!-- <image :src="ShareQrImage" style="width: 100%;height: 100%;"></image> -->
		<view style="text-align: center;margin-top: 30upx;">
			<button size="mini" style="width: 25%; font-size: 30rpx;" @click="setQRCodeTime(300000)" type="default">刷新</button>
			<button size="mini" style="margin-left:25rpx; 25%;font-size: 30rpx;" type="default" @click="ShareQr">分享二维码</button>
		</view>

		<!-- {{ width }} -->
		<u-popup v-model="popShow" mode="bottom" length="40%">
			<view class="popup_show">
				<view style="font-size: 35rpx;font-weight: 600;text-align: center;">
					有效期设置
				</view>
				<view class="time_btn">
					快捷设置：
					<u-button size="mini" type="success" @click="setQRCodeTime(600000)">10分钟</u-button>
					<u-button size="mini" type="success" @click="setQRCodeTime(1800000)">30分钟</u-button>
					<u-button size="mini" type="success" @click="setQRCodeTime(3600000)">60分钟</u-button>
				</view>
				<view class="">
					当前设置时间：{{showTime}}
					<u-button style="margin-left: 30rpx;" @click="pickerShow = true" type="primary" size="mini">自定义时间</u-button>
				</view>
				<view style="margin-left: 10%;width: 80%;">
					<u-button size="default" type="success" @click="btnSetTime">确定</u-button>
				</view>

			</view>
		</u-popup>

		<!-- 弹出分享层 -->
		<u-modal width="80%" :show-title='false' :show-cancel-button='true' cancel-text='关闭' @confirm='shareImg' confirm-text='分享'
		 v-model="modelShow" :content="content">
			<image v-if="ShowCoverimage" class='coveimg' :style="{width: driveWidth*.8+'px',height: (driveWidth*.8)*1.4+'px'}"
			 @click="shareImg" mode='aspectFit' :src="ShareQrImage"></image>
		</u-modal>
		<u-picker mode="time" v-model="pickerShow" :default-time="showTime" :params="params" @confirm='setTime'></u-picker>
		<canvas id="sharecanvas" :style="{width: driveWidth*.8+'px',height: (driveWidth*.8)*1.4+'px'}" canvas-id="sharecanvas"></canvas>
	</view>
</template>

<script>
	import uniNavBar from "../../components/uni-nav-bar/uni-nav-bar.vue"
	import uQRCode from '../../js_sdk/Sansnn-uQRCode/uqrcode.js';
	import moment from 'moment';
	import http from '../../common/vmeitime-http/index.js';
	import {getQrCode} from '../../utils/getCardCode.js'
	export default {
		components: { uniNavBar },
		data() {
			return {
				qrtext: 'fcard',
				width: 250,
				remainingTime: '', //剩余时间
				QRTime1: null,
				QRTime2: null,
				QrNowTime: null, //二维码时间
				popShow: false,
				modelShow: false,
				QrImage: null,
				ShareQrImage: null,
				ShareQrImg: '',
				driveWidth: 320,
				ShowCoverimage: false,
				showTime: null,
				pickerShow: false,
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true
				},
				cardId: '',
			};
		},
		created() {
			const {
				windowWidth,
				windowHeight
			} = uni.getSystemInfoSync();
			this.width = windowWidth * 0.75;
			this.driveWidth = windowWidth;
			
		},
		onShow() {
			this.cardId = uni.getStorageSync('Cardid')?uni.getStorageSync('Cardid'):''
			this.popShow = false;
			this.setQrCode();
			this.popShow = false;
		},
		onShareAppMessage(res) {
		if (res.from === 'button') {// 来自页面内分享按钮
		  console.log(res.target)
		}
		return {
		  title: this.$Fpublic.company,
		  path: '/pages/index/index'
		}
	  },
		methods: {
			moment: moment,
			createQrcode(time = (Math.round(new Date().getTime() / 1) + 300000)) {
				// 判断设置的时间
				console.log(time+'');
				uni.setStorageSync('asdfsadf', time);
				uni.setStorageSync('QrTime', time);
				this.QrNowTime = time;
				let that = this;
				let parma = {
					timeStamp: time,
					cardNumber: that.$Fpublic.cardId
				};
				getQrCode(time,this.cardId?this.cardId:'12345678', 1).then(res => {
					console.log(res)
					that.qrtext = res;
					that.make();
				}).catch(err => {
					that.qrtext = '';
					that.make();
				})
			},
			/**
			 * 自动轮询
			 * */
			setQrCode() {
				console.log(uni.getStorageSync('QrTime'))
				// uni.setStorageSync('QrTime', '1599901930150');
				if (uni.getStorageSync('QrTime')) {
					let oldTime = uni.getStorageSync('QrTime');
					console.log(moment(oldTime).diff(moment(), 'seconds'));
					if ((moment(oldTime).diff(moment(), 'seconds')) > 0) {
						this.remainingTime = moment(oldTime).diff(moment(moment().format('X') * 1000), 'seconds');
						console.log(this.remainingTime);
						this.createQrcode(oldTime);

						clearTimeout(this.QRTime1);
						this.QRTime1 = setTimeout(() => {
							this.setQrCode();
						}, this.remainingTime * 1000);
					} else {
						this.createQrcode(Math.round(new Date().getTime() / 1) + 300000);
						clearTimeout(this.QRTime1);
						this.remainingTime = 300000;
						this.QRTime1 = setTimeout(() => {
							this.setQrCode();
						}, 300000);
					}
				} else {
					console.log(Math.round(new Date().getTime()) + 300000)
					this.createQrcode(Math.round(new Date().getTime() / 1) + 300000);
					clearTimeout(this.QRTime1);
					this.remainingTime = 300000;
					this.QRTime1 = setTimeout(() => {
						this.setQrCode();
					}, 300000);

				}
			},
			/**
			 * 设置时间
			 * */
			setQRCodeTime(time = 10000) {
				try{
				clearTimeout(this.QRTime2);
				clearTimeout(this.QRTime1);
				console.log(time)
				this.createQrcode((moment().format('x')-0) + time);
				this.QRTime2 = setTimeout(() => {
					this.setQrCode();
				}, time);
				this.popShow = false;
				}catch(e){
					//TODO handle the exception
					console.log(e);
				}
				
			},
			btnSetTime() {
				let time = moment(this.showTime).format('x') - moment().format('x');
				this.setQRCodeTime(time)
			},
			setTime(val) {
				console.log(val);
				let time = `${val.year}-${val.month}-${val.day} ${val.hour}:${val.minute}:${val.second}`
				this.showTime = moment(time).format('YYYY-MM-DD HH:mm:ss');
				console.log(this.showTime)
			},
			popShowFun() {
				this.popShow = true;
				// console.log(this.popShow)
			},
			//生成二维码图片
			ShareQr() {
				let that = this;
				uni.showToast({
					title: '正在生成图片,请稍后',
					duration: 10000,
					icon: 'loading'
				});
				that.ShareQrImage = that.QrImage;
				console.log('开始生成图片')
				that.canvasDraw()
			},
			/**
			 * 绘画canvas
			 * **/
			canvasDraw() {
				// var context = 
				this.ShowCoverimage = false;
				let ctx = uni.createCanvasContext('sharecanvas');
				let that = this;
				// uni.downloadFile({
				// url: that.QrImage,
				// success: function(res) {
				console.log('获得图片')
				ctx.save()
				ctx.beginPath()

				let canvaswidths = that.driveWidth * .8;
				let qrwidth = canvaswidths - 80; //二维码宽度
				// ctx.drawImage(res.path, 0, 60, that.data.canvasWidth, 400)
				ctx.width = canvaswidths;
				ctx.height = canvaswidths * 1.4;
				ctx.clearRect(0, 10, canvaswidths, canvaswidths * 1.4);
				ctx.fillStyle = "#fff";
				ctx.fillRect(0, 20, canvaswidths, canvaswidths * 1.4);
				ctx.drawImage(that.QrImage, (canvaswidths - qrwidth) / 2, 60, qrwidth, qrwidth) //二维码
				ctx.setTextAlign('center') // 文字居中
				ctx.setFillStyle('#000000') // 文字颜色：黑色
				ctx.setFontSize(15) // 文字字号：22px
				ctx.fillText('二维码有效期：' + moment(that.QrNowTime).format('YYYY-MM-DD HH:mm:ss'), canvaswidths / 2,
					canvaswidths * 1.1)
				ctx.fillText('点击图片长按分享', canvaswidths / 2, canvaswidths * 1.2 + 20)
				ctx.fillText('二维码门禁', canvaswidths / 2, 60)
				ctx.stroke()
				ctx.draw()
				setTimeout(function() {
					uni.canvasToTempFilePath({
						canvasId: 'sharecanvas',
						success: function(res) {
							console.error(res)

							var tempFilePath = res.tempFilePath;
							console.log(tempFilePath);
							that.ShareQrImg = tempFilePath;
							const imgData = uni.getFileSystemManager().readFileSync(tempFilePath, 'base64');
							const base64 = 'data:image/png;base64,' + imgData;
							console.log(base64)
							that.ShareQrImage = base64;
							that.modelShow = true;
							uni.hideToast();
							that.ShowCoverimage = true;
						},
						fail: function(res) {
							uni.hideToast();
							console.error(res);
						},
						complete: (res) => {
							uni.hideToast();
							console.error(res)
						}
					})
				}, 1000)
				// },
				// complete: (res) => {
				// uni.hideToast();
				// console.error(res)
				// }
				// })
			},
			// 生成二维码
			make() {
				let that = this;
				uQRCode.make({
					canvasId: 'qrcode',
					componentInstance: this,
					text: this.qrtext ? this.qrtext : 'fcard',
					size: this.width,
					margin: 10,
					backgroundColor: '#ffffff',
					foregroundColor: '#000000',
					fileType: 'jpg',
					correctLevel: uQRCode.defaults.correctLevel,
					success: res => {
						console.log(res);
						that.QrImage = res;
					}
				});
			},
			//分享图片
			shareImg() {
				// uni.share({
				//     provider: "weixin",
				//     scene: "WXSceneSession",
				//     type: 2,
				//     imageUrl: this.ShareQrImage,
				//     success: function (res) {
				//         console.log("success:" + JSON.stringify(res));
				//     },
				//     fail: function (err) {
				//         console.log("fail:" + JSON.stringify(err));
				//     }
				// });
				// uni.share({
				//     provider: "weixin",
				//     scene: "WXSenceTimeline",
				//     type: 2,
				//     imageUrl: this.ShareQrImg,
				//     success: function (res) {
				//         console.log("success:" + JSON.stringify(res));
				//     },
				//     fail: function (err) {
				//         console.log("fail:" + JSON.stringify(err));
				//     }
				// });
				let that = this;
				uni.previewImage({
					urls: [that.ShareQrImg],
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			setCard() {
				uni.navigateTo({
					url: '/pages/SetCardNum/SetCardNum'
				})
			},
			Tohome(){
				uni.navigateTo({
					url: '/pages/index/SetCardNum'
				})
			}
		},
		watch: {
			QrNowTime(n) {
				console.log(n);
				this.showTime = moment(n).format('YYYY-MM-DD HH:mm:ss')
			},

		}
	};
</script>

<style lang="scss" scoped>
	.fcard {
		.imgBox {
			text-align: center;
			position: relative;
			margin: 50upx 0;
			text {
				position: absolute;
				top: 0;
				left: 100upx;
				text-decoration: underline;
				color: #007AFF;
				font-size: 30upx;
				
			}

		}
	}

	.body {
		width: 100%;
		height: 100%;
		overflow: hidden;
		overflow-y: auto;
		position: relative;

		#qrcode {
			position: absolute;
			left: -100%;
			width: 100%;
			height: 100%;
			top: 0;
		}

		#sharecanvas {
			position: absolute;
			left: 100%;
			width: 100%;
			height: 100%;
			top: 0;
		}

		.popup_show {
			>view {
				margin-top: 30rpx;
				margin-left: 5%;
			}
		}

		.time_btn {
			>u-button {
				margin-left: 30rpx;
			}
		}
	}
</style>
